<template>
  <div class="editBillingRules-page">
    <!-- <breadcrumb /> -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>路边停车</el-breadcrumb-item>
      <el-breadcrumb-item>编辑计费规则</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="table-container">
      <h3 style="margin-bottom: 20px">编辑计费规则</h3>
      <el-form
        ref="editFormRef"
        :rules="rules"
        :model="editForm.data"
        label-width="160"
      >
        <el-row>
          <el-form-item label="规则名称" prop="ruleName">
            <el-input
              v-model="editForm.data.ruleName"
              style="width: 320px"
              placeholder="请输入规则名称"
            />
          </el-form-item>
          <el-form-item label="首停免费时长" prop="freeDuration">
            <el-input
              v-model="editForm.data.freeDuration"
              style="width: 320px"
              placeholder="请输入首停免费时长"
              ><template #append>分钟</template></el-input
            >
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="24小时收费上限" prop="dayLimit">
            <el-input
              v-model="editForm.data.dayLimit"
              style="width: 320px"
              placeholder="0元表示不封顶"
            >
              <template #append>元</template></el-input
            >
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="editForm.data.remark"
              style="width: 320px"
              placeholder="请输入备注"
              type="textarea"
              :rows="1"
            />
          </el-form-item>
        </el-row>
        <div style="display: flex; align-items: center; margin-bottom: 16px">
          <h3>计费规则明细</h3>
          <el-tooltip placement="top">
            <template #content>
              需要分别配置每种车辆类型工作日和非工作日的收费标准；<br />没有配置的时段默认为免费；<br />收费时段若跨00:00点，则请分为两段配置，<br />如19:00-07:00，则请分别配置“19:00-23:59和00:00-07:00”。
            </template>

            <img class="doubt-img" :src="doubt" alt="" />
          </el-tooltip>
          <el-button type="primary" @click="getEditFlag">新增</el-button>
        </div>
        <div>
          <el-table
            v-if="table.data.length > 0"
            :data="table.data"
            :loading="table.loading"
            style="width: 100%"
            :header-cell-style="{
              background: '#F1F1F1',
              'font-size': '14px',
              'font-weight': 600,
              color: '#333333',
            }"
            :cell-style="{
              'font-size': '14px',
              'font-weight': 400,
              color: '#333333',
            }"
          >
            <el-table-column prop="billingDateType" label="日期类型">
              <template #default="scope">
                {{ scope.row.billingDateType == 1 ? "工作日" : "非工作日" }}
              </template>
            </el-table-column>
            <el-table-column prop="vehicleType" label="车辆类型">
              <template #default="scope">
                {{
                  scope.row.vehicleType == 1
                    ? "大型车"
                    : scope.row.vehicleType == 2
                    ? "小型车"
                    : "新能源"
                }}
              </template>
            </el-table-column>
            <el-table-column label="收费时间" min-width="120">
              <template #default="scope">
                {{ scope.row.startTime }}-{{ scope.row.endTime }}
              </template>
            </el-table-column>
            <el-table-column prop="rateDesc" label="计费规则" min-width="260" />
            <el-table-column label="封顶金额（元）" min-width="140">
              <template #default="scope">
                <span v-if="scope.row.timeLimit == 0">不封顶</span>
                <span v-else>{{ scope.row.timeLimit }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="code"
              label="操作"
              min-width="100"
              fixed="right"
            >
              <template #default="scope">
                <el-button
                  @click="editData(scope.row)"
                  type="primary"
                  size="small"
                  link
                  style="color: #007aff"
                  >编辑
                </el-button>
                <el-button
                  @click="deleteData(scope.row)"
                  type="primary"
                  size="small"
                  link
                  style="color: #007aff"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="editFlag" class="billing-detail">
            <h3>明细</h3>
            <el-form
              ref="billingDetailsRef"
              :rules="billingDetailsRules"
              :model="billingDetails.data"
              label-width="160"
            >
              <el-form-item label="日期类型">
                <el-radio-group v-model="billingDetails.data.billingDateType">
                  <el-radio
                    v-for="item in billingDateType.data"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.name }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="车辆类型">
                <el-radio-group v-model="billingDetails.data.vehicleType">
                  <el-radio
                    v-for="item in vehicleType.data"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.name }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-row>
                <el-form-item label="收费开始时间" prop="startTime">
                  <el-time-select
                    v-model="billingDetails.data.startTime"
                    style="width: 260px"
                    :max-time="billingDetails.data.endTime"
                    class="mr-4"
                    placeholder="请选择开始时间"
                    start="00:00"
                    step="00:15"
                    end="24:00"
                  />
                </el-form-item>
                <el-form-item label="收费结束时间" prop="endTime">
                  <el-time-select
                    v-model="billingDetails.data.endTime"
                    style="width: 260px"
                    :min-time="billingDetails.data.startTime"
                    placeholder="请选择结束时间"
                    start="00:00"
                    step="00:15"
                    end="24:00"
                  />
                </el-form-item>
              </el-row>
              <el-form-item label="时段封顶金额" prop="timeLimit">
                <el-input
                  v-model="billingDetails.data.timeLimit"
                  style="width: 260px"
                  placeholder="0元表示不封顶"
                >
                  <template #append>元</template>
                </el-input>
              </el-form-item>
              <el-table
                :data="priceList.data"
                :loading="billingDetails.loading"
                :header-cell-style="{
                  background: '#F1F1F1',
                  'font-size': '14px',
                  'font-weight': 600,
                  color: '#333333',
                }"
                :cell-style="{
                  'font-size': '14px',
                  'font-weight': 400,
                  color: '#333333',
                }"
              >
                <el-table-column
                  prop="billingDuration"
                  label="计费时长（分钟）"
                  min-width="90"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.billingDuration"
                      style="width: 180px"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="cost" label="费用（元）" min-width="90">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.cost"
                      style="width: 180px"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="billingUnit"
                  label="计费单位(分钟)"
                  min-width="90"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.billingUnit"
                      style="width: 180px"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="费用概述" min-width="110">
                  <template #default="scope">
                    <!-- <span v-if="scope.row.billingUnit && scope.row.cost">
                      <span v-if="scope.$index === 0">{{
                        (scope.row.rateDesc =
                          "首" +
                          scope.row.billingUnit +
                          "分钟" +
                          scope.row.cost +
                          "元")
                      }}</span>
                      <span v-else>
                        {{
                          (scope.row.rateDesc =
                            "之后" +
                            scope.row.billingUnit +
                            "分钟" +
                            scope.row.cost +
                            "元")
                        }}
                      </span>
                    </span> -->
                    <el-input
                      v-model="scope.row.rateDesc"
                      style="width: 240px"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" min-width="40" fixed="right">
                  <template #default="scope">
                    <el-button
                      v-if="scope.$index > 0"
                      @click="deletebilling(scope.$index)"
                      type="primary"
                      size="small"
                      link
                      style="color: #007aff"
                      >删除
                    </el-button>
                    <el-button
                      v-if="scope.$index == 0"
                      @click="editbilling()"
                      type="primary"
                      size="small"
                      link
                      style="color: #007aff"
                      >添加一行
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-form-item>
                <div class="footer">
                  <div></div>
                  <div class="search-btn">
                    <el-button
                      class="reset-btn"
                      @click="resetForm2(billingDetailsRef)"
                      >取 消
                    </el-button>
                    <el-button
                      class="confirm-btn"
                      @click="submitForm2(billingDetailsRef)"
                      >确 认
                    </el-button>
                  </div>
                </div>
              </el-form-item>
            </el-form>
          </div>
          <div v-else></div>
        </div>
        <el-form-item>
          <div class="footer">
            <div></div>
            <div class="search-btn">
              <el-button class="reset-btn" @click="resetForm(editFormRef)"
                >重 置
              </el-button>
              <el-button class="confirm-btn" @click="submitForm(editFormRef)"
                >确 认
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import breadcrumb from "@/components/breadcrumb/index.vue";
import {
  getSingleBillingRule,
  getEditBillingRules,
} from "../request.js";
import { reactive, ref, onMounted } from "vue";
import doubt from "@/assets/image/doubt.png";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
// 弹窗
const editFlag = ref(false);

const getEditFlag = () => {
  editFlag.value = true;
};

const billingDetailsRef = ref("");

const billingDetails = reactive({
  data: {},
  total: 0,
  loading: true,
});

const billingDetailsRules = reactive({
  startTime: [
    {
      required: true,
      message: "请选择收费开始时间",
      trigger: "change",
    },
  ],
  endTime: [
    {
      required: true,
      message: "请选择收费结束时间",
      trigger: "change",
    },
  ],
  timeLimit: [
    {
      required: true,
      message: "请输入时段封顶金额",
      trigger: "blur",
    },
  ],
});

const vehicleType = reactive({
  data: [
    {
      id: 1,
      name: "大型车",
    },
    {
      id: 2,
      name: "小型车",
    },
    {
      id: 3,
      name: "新能源车",
    },
  ],
});

const billingDateType = reactive({
  data: [
    {
      id: 1,
      name: "工作日",
    },
    {
      id: 2,
      name: "非工作日",
    },
  ],
});
const priceList = reactive({
  data: [{}],
  total: 0,
  loading: true,
});
// 表格
const table = reactive({
  data: [],
  total: 0,
  loading: true,
});

const editFormRef = ref("");

const editForm = reactive({
  data: {},
});

const editbilling = () => {
  priceList.data.push({ aid: generateUniqueId() });
};
const deletebilling = (index) => {
  priceList.data.splice(index, 1);
};
const rules = reactive({
  ruleName: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
  freeDuration: [
    { required: true, message: "请输入首停免费时长", trigger: "blur" },
  ],
  dayLimit: [
    { required: true, message: "请输入24小时收费上限", trigger: "blur" },
  ],
});

const submitForm = (formEl) => {
  let datavehicleList = [];
  for (let type of billingDateType.data) {
    for (let vehicle of vehicleType.data) {
      datavehicleList.push({
        billingDateType: type.id,
        vehicleType: vehicle.id,
      });
    }
  }
  let difference = datavehicleList.filter(
    (item1) =>
      !table.data.some(
        (item2) =>
          item1.billingDateType === item2.billingDateType &&
          item1.vehicleType === item2.vehicleType
      )
  );
  console.log(difference);
  /* table.data.forEach(data=>{
    data[data[0].cost+","+data[0].billingUnit] = data[1].cost+","+data[1].billingUnit
  })*/
  console.log(table.data, "aaaaaaaaaa");
  editForm.data.ruleRates = table.data;

  for (let item of difference) {
    let dataTypeName = billingDateType.data.find(
      (billing) => billing.id == item.billingDateType
    ).name;
    console.log(dataTypeName);
    let vehicleTypeName = vehicleType.data.find(
      (ehicle) => ehicle.id == item.vehicleType
    ).name;
    ElMessage({
      type: "error",
      message:
        "您还未配置" + dataTypeName + "中" + vehicleTypeName + "的规则明细！",
    });
    break;
  }
  console.log("editForm.data ===>", editForm.data);

  // return;
  if (difference.length <= 0) {
    if (!formEl) return;
    formEl.validate(async (valid) => {
      if (valid) {
        await getEditBillingRules(editForm.data).then((res) => {
          console.log("res ===>", res);
          if (res.data.code === 0) {
            ElMessage({
              type: "success",
              message: res.data.result,
            });
            router.push("/road/config/chargingRule");
          }
        });
      }
    });
  }
};

const resetForm = (formEl) => {
  // if (!formEl) return;
  editForm.data = {};
  billingDetails.data = {};
  priceList.data = [{}];
  editForm.data.ruleRates = [];
  table.data = [];
  formEl.resetFields();
};
const editData = (row) => {
  // billingDetails.data = [{},{}];
  // billingDetails.data = row;
  Object.assign(billingDetails.data, row);
  priceList.data = [];
  let rate = billingDetails.data.rate.split(";");
  let rateDesc = billingDetails.data.rateDesc.split(";");
  for (var index = 0; index < rate.length; index++) {
    let infodata = {
      billingDuration: rate[index].split(",")[0],
      cost: rate[index].split(",")[1],
      billingUnit: rate[index].split(",")[2],
      rateDesc: rateDesc[index],
    };
    priceList.data.push(infodata);
  }
  //priceList.data = billingDetails.data.priceList;
  editFlag.value = true;
};
const deleteData = (row) => {
  let index = table.data.findIndex((item) => item.aid === row.aid);
  if (index != -1) {
    table.data.splice(index, 1);
  }
};
const submitForm2 = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      const detail = billingDetails.data;
      let rateDesc = "";
      let rate = "";
      let isFirst = true;
      priceList.data.forEach((item) => {
        rateDesc = rateDesc + ";" + item.rateDesc;
        const itemRate =
          item.billingDuration + "," + item.cost + "," + item.billingUnit;
        if (!isFirst) {
          rate += ";" + itemRate;
        } else {
          // 如果是第一个元素，直接拼接，不添加冒号
          rate += itemRate;
          isFirst = false; // 确保下次迭代不会再次认为是第一个元素
        }
      });
      console.log(rate);
      billingDetails.data.rateDesc = rateDesc.replace(";", "");
      billingDetails.data.rate = rate;
      billingDetails.data.priceList = priceList.data;
      console.log("billingDetails.data ===>", billingDetails.data);

      let state = true;
      for (let item of table.data) {
        if (
          item.billingDateType == detail.billingDateType &&
          item.vehicleType == detail.vehicleType &&
          item.id != detail.id
        ) {
          if (detail.startTime < item.endTime) {
            // ElMessage({
            //   type: "error",
            //   message:
            //     detail.dateType +
            //     "中" +
            //     detail.vehicleType +
            //     "的收费时段重复配置，请检查!",
            // });
            ElMessage({
              type: "error",
              message:
                detail.billingDateType +
                "中" +
                detail.vehicleType +
                "的开始时间必须大于或等于上一次的结束时间!",
            });
            state = false;
            break;
          }
        }
      }
      if (state) {
        console.log(table.data, "aaa");
        console.log(detail, "bbb");
        let index = table.data.findIndex((item) => item.aid === detail.aid);
        console.log(index, "ccc");
        if (index != -1) {
          // table.data.splice(index, 1);
          Object.assign(table.data[index], billingDetails.data);
          // table.data[index] = billingDetails.data;
        } else {
          billingDetails.data.aid = generateUniqueId();
          table.data.push(billingDetails.data);
        }
        priceList.data = [];
        editFlag.value = false;
      }
    }
  });
};

const resetForm2 = (formEl) => {
  if (!formEl) return;
  billingDetails.data = {};
  priceList.data = [{}];
  editFlag.value = false;
  formEl.resetFields();
};
let counter = 0;
function generateUniqueId() {
  const timestamp = Date.now().toString(36); // 转换为36进制，减小长度
  const random = Math.random().toString(36).substr(2, 5); // 生成5位随机字符串
  counter++;
  return `${timestamp}-${random}-${counter}`;
}
onMounted(async () => {
  // 获取浏览器数据解密
  const encodedData = route.query.data;
  if (encodedData) {
    try {
      const decodedData = decodeURIComponent(encodedData);
      const id = JSON.parse(decodedData);
      await getSingleBillingRule(id).then((res) => {
        console.log("res ===>", res);
        editForm.data = res.data.result;
        editForm.data.ruleId = id;
        table.data = res.data.result.ruleRates;
        table.data.forEach((item) => {
          item.aid = generateUniqueId();
        });
      });
    } catch (error) {
      console.error("Error parsing row data:", error);
    }
  }
});
</script>

<style lang="less" scoped>
.table-container {
  margin-top: 16px;
  min-height: 100%;
  padding: 24px;
  background: #fff;
  border-radius: 6px;
}

.footer {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-top: 24px;
}

.search-btn {
  display: flex;
}

.reset-btn {
  width: 65px;
  height: 32px;
  background: #ffffff;
  border-radius: 2px;
  border: 1px solid #d9d9d9;
  font-weight: 400;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
}

.confirm-btn {
  width: 65px;
  height: 32px;
  background: #007aff;
  border-radius: 2px;
  font-weight: 400;
  font-size: 14px;
  color: #ffffff;
}

.doubt-img {
  width: 16px;
  height: 16px;
  margin-left: 6px;
  margin-right: 6px;
}
.billing-detail {
  background: #f2f7fc;
  padding: 20px;
  margin-top: 24px;
}
</style>
